package com.xiegang.servicessepush.controller;

import com.xiegang.internalcommon.util.SsePreFixUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xieGang
 * @description
 * @date 2023/4/11 18:54
 **/

@RestController
@Slf4j
public class SseController {

    public static Map<String,SseEmitter> stringSseEmitterMap = new HashMap<>();
    @GetMapping("/connect")
    public SseEmitter connect(@RequestParam Long userId,@RequestParam String identity){
        log.info("用户id："+userId+",身份："+identity);

        String sseMapKey = SsePreFixUtils.generatorSseKey(userId, identity);

        SseEmitter sseEmitter = new SseEmitter(0l);
        stringSseEmitterMap.put(sseMapKey,sseEmitter);
        return sseEmitter;
    }

    @GetMapping("/push")
    public String push(@RequestParam Long userId,@RequestParam String identity,@RequestParam String content){
        log.info("用户id："+userId+",身份："+identity);
        String sseMapKey = SsePreFixUtils.generatorSseKey(userId, identity);

        if(stringSseEmitterMap.containsKey(sseMapKey)){
            SseEmitter sseEmitter = stringSseEmitterMap.get(sseMapKey);
            try {
                sseEmitter.send(content);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return "给用户:"+sseMapKey+"，发送了消息："+content;
        }
        return "找不到连接";
    }

    @GetMapping("/close")
    public String close(@RequestParam Long userId,@RequestParam String identity){
        String sseMapKey = SsePreFixUtils.generatorSseKey(userId, identity);
        if(stringSseEmitterMap.containsKey(sseMapKey)){
            stringSseEmitterMap.remove(sseMapKey);
        }
        System.out.println("driverId"+sseMapKey+"关闭");
        return "关闭了用户:"+sseMapKey+"的连接";
    }
}
